<template>
  <div class="dashboard-container">
    <!-- 帆软报表全屏显示 -->
    <iframe
      v-show="!showError && !useRedirect"
      ref="fanruanIframe"
      :src="fanruanUrl"
      frameborder="0"
      class="fanruan-fullscreen"
      @load="onFanruanLoad"
      @error="onFanruanError"
    ></iframe>
    
    <!-- 加载提示 -->
    <div v-if="isLoading && !showError && !useRedirect" class="loading-overlay">
      <el-icon class="loading-icon" :size="50"><Loading /></el-icon>
      <div class="loading-text">正在加载帆软报表...</div>
      <div class="loading-hint">{{ loadingHint }}</div>
    </div>
    
    <!-- 跨域提示（X-Frame-Options错误） -->
    <div v-if="useRedirect" class="redirect-overlay">
      <el-icon class="redirect-icon" :size="80"><Link /></el-icon>
      <div class="redirect-title">检测到跨域限制</div>
      <div class="redirect-message">
        帆软服务器设置了安全策略，不允许在iframe中嵌入。<br/>
        请点击下方按钮在新窗口中打开报表。
      </div>
      <div class="redirect-actions">
        <el-button type="primary" size="large" @click="openInNewWindow">
          <el-icon><Link /></el-icon>
          <span>在新窗口中打开帆软报表</span>
        </el-button>
        <el-button @click="showConfigDialog = true">
          <el-icon><Setting /></el-icon>
          <span>修改配置</span>
        </el-button>
      </div>
      <div class="redirect-hint">
        <el-alert
          title="解决方案"
          type="info"
          :closable="false"
        >
          <template #default>
            <p>如需在页面中嵌入显示，请修改帆软服务器的 X-Frame-Options 配置。</p>
            <p>详细步骤请参考《帆软X-Frame-Options配置修改指南.md》</p>
          </template>
        </el-alert>
      </div>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="showError && !useRedirect" class="error-overlay">
      <el-icon class="error-icon" :size="80"><WarningFilled /></el-icon>
      <div class="error-title">帆软报表加载失败</div>
      <div class="error-message">{{ errorMessage }}</div>
      <div class="error-solutions">
        <h3>可能的解决方案：</h3>
        <ol>
          <li>检查帆软服务是否已启动（端口 8075）</li>
          <li>检查服务器地址：{{ fanruanServerUrl }}</li>
          <li>检查网络连接和防火墙设置</li>
          <li>确认帆软报表URL是否正确</li>
          <li>如果使用localhost，确保在本地访问</li>
        </ol>
      </div>
      <div class="error-actions">
        <el-button type="primary" @click="retryLoad" :loading="isRetrying">
          <el-icon><RefreshRight /></el-icon>
          <span>重新加载</span>
        </el-button>
        <el-button @click="showConfigDialog = true">
          <el-icon><Setting /></el-icon>
          <span>修改配置</span>
        </el-button>
      </div>
    </div>
    
    <!-- 配置对话框 -->
    <el-dialog
      v-model="showConfigDialog"
      title="配置帆软报表地址"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form :model="configForm" label-width="140px">
        <el-form-item label="帆软报表完整URL">
          <el-input
            v-model="configForm.fullUrl"
            type="textarea"
            :rows="3"
            placeholder="例如: http://10.223.9.4:8075/webroot/decision/view/duchamp?viewlet=%25E5%25BA%2593%25E5%25AD%2598%25E4%25BC%2598%25E5%258C%2596%252F%25E5%25BA%2593%25E5%25AD%2598%25E4%25BC%2598%25E5%258C%2596.fvs&page_number=1"
          />
        </el-form-item>
        <el-form-item label="说明">
          <el-alert
            title="从帆软报表页面直接复制完整URL即可"
            type="info"
            :closable="false"
          />
        </el-form-item>
        <el-form-item label="服务器地址">
          <el-text type="info" size="small">
            {{ fanruanServerUrl }}
          </el-text>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showConfigDialog = false">取消</el-button>
        <el-button type="primary" @click="saveConfig">保存并重新加载</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, getCurrentInstance } from 'vue';
import * as signalR from '@microsoft/signalr';
import { Loading, WarningFilled, RefreshRight, Setting, Link } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();

// SignalR连接
let connection = null;

// 响应式数据
const isLoading = ref(true);
const showError = ref(false);
const isRetrying = ref(false);
const useRedirect = ref(false);
const fanruanIframe = ref(null);
const loadingHint = ref('正在连接帆软服务器...');
const errorMessage = ref('');
const showConfigDialog = ref(false);

// 帆软配置
const configForm = ref({
  // 直接使用完整URL
  fullUrl: 'http://10.223.9.4:8075/webroot/decision/view/duchamp?viewlet=%25E5%25BA%2593%25E5%25AD%2598%25E4%25BC%2598%25E5%258C%2596%252F%25E5%25BA%2593%25E5%25AD%2598%25E4%25BC%2598%25E5%258C%2596.fvs&page_number=1'
});

// 帆软报表地址
const fanruanUrl = ref('');
const fanruanServerUrl = computed(() => {
  try {
    const url = new URL(configForm.value.fullUrl);
    return `${url.protocol}//${url.host}`;
  } catch (e) {
    return 'localhost:8075';
  }
});

// 预览URL（直接使用完整URL）
const previewUrl = computed(() => {
  return configForm.value.fullUrl || '';
});

// 初始化配置
const initConfig = () => {
  // 从localStorage加载配置
  const savedConfig = localStorage.getItem('fanruan_config');
  if (savedConfig) {
    try {
      const config = JSON.parse(savedConfig);
      configForm.value = config;
    } catch (e) {
      console.warn('加载帆软配置失败，使用默认配置');
    }
  }
  
  // 生成完整URL
  fanruanUrl.value = previewUrl.value;
  console.log('📊 帆软报表地址:', fanruanUrl.value);
};

/**
 * 初始化SignalR连接，用于实时刷新帆软报表
 */
const initSignalR = async () => {
  try {
    console.log('🚀 正在初始化SignalR连接...');
    
    // 获取API基础地址（与axios保持一致）
    const apiBaseUrl = window.ipAddress || 'http://localhost:9991/';
    const signalRUrl = apiBaseUrl + 'api/signalr/DashboardHub';
    
    console.log('📡 SignalR连接地址:', signalRUrl);
    
    // 创建SignalR连接
    connection = new signalR.HubConnectionBuilder()
      .withUrl(signalRUrl, {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets
      })
      .withAutomaticReconnect([0, 1000, 3000, 5000, 10000]) // 自动重连策略
      .configureLogging(signalR.LogLevel.Information)
      .build();

    // 监听数据更新事件 - 接收数据但不刷新iframe（避免闪烁）
    connection.on('ReceiveDashboardUpdate', (data) => {
      console.log('📡 收到大屏数据更新:', data);
      
      // 帆软报表会自动刷新数据，不需要重新加载整个iframe
      // 如果帆软报表支持API更新，可以调用帆软的刷新API
      // 例如：fanruanIframe.value?.contentWindow?.FR?.refreshData();
      
      // 暂时注释掉刷新逻辑，避免画面闪烁
      // refreshFanruanReport();
    });

    // 连接关闭事件
    connection.onclose((error) => {
      console.log('❌ SignalR连接已断开', error);
    });

    // 重连中事件
    connection.onreconnecting((error) => {
      console.log('🔄 SignalR正在重连...', error);
    });

    // 重连成功事件
    connection.onreconnected((connectionId) => {
      console.log('✅ SignalR已重新连接, ConnectionId:', connectionId);
      // 重新加入大屏数据组
      connection.invoke('JoinGroup', 'Dashboard').catch(err => {
        console.error('❌ 重新加入大屏数据组失败:', err);
      });
    });

    // 启动连接
    await connection.start();
    console.log('✅ SignalR连接成功, ConnectionId:', connection.connectionId);
    
    // 加入大屏数据组
    await connection.invoke('JoinGroup', 'Dashboard');
    console.log('✅ 已加入大屏数据实时更新组');
    
    // 通知服务器启动定时推送（每5秒更新一次）
    try {
      await proxy.http.post('/api/Dashboard/StartAutoPush');
      console.log('✅ 已启动服务器端定时推送（5秒/次）');
    } catch (error) {
      console.warn('⚠️ 启动定时推送失败（服务器可能未实现此接口）:', error.message);
    }
    
  } catch (error) {
    console.error('❌ SignalR连接失败:', error);
    // 如果SignalR连接失败，降级为定时轮询刷新
    startPollingRefresh();
  }
};

/**
 * 刷新帆软报表（重新加载iframe）
 */
const refreshFanruanReport = () => {
  if (fanruanIframe.value) {
    console.log('🔄 刷新帆软报表...');
    // 添加时间戳防止缓存
    const url = new URL(fanruanUrl.value);
    url.searchParams.set('_t', Date.now());
    fanruanIframe.value.src = url.toString();
  }
};

/**
 * 降级方案：定时轮询刷新（当SignalR不可用时）
 * 注意：已禁用自动刷新，避免画面闪烁
 */
let pollingTimer = null;
const startPollingRefresh = () => {
  console.log('⚠️ SignalR不可用');
  console.log('💡 帆软报表会自动刷新数据，无需手动刷新iframe');
  
  // 禁用定时刷新，避免画面闪烁
  // 帆软报表本身支持数据自动刷新，不需要重新加载整个iframe
  
  // 如果确实需要定时刷新，取消下面的注释
  /*
  // 清除已存在的定时器
  if (pollingTimer) {
    clearInterval(pollingTimer);
  }
  
  // 每30秒刷新一次
  pollingTimer = setInterval(() => {
    refreshFanruanReport();
  }, 30000);
  */
};

/**
 * 在新窗口中打开帆软报表
 */
const openInNewWindow = () => {
  window.open(fanruanUrl.value, '_blank');
  proxy.$message.success('已在新窗口中打开帆软报表');
};

/**
 * 帆软报表加载完成
 */
const onFanruanLoad = () => {
  console.log('✅ 帆软报表加载完成');
  isLoading.value = false;
  showError.value = false;
  useRedirect.value = false;
};

/**
 * 帆软报表加载失败
 */
const onFanruanError = (error) => {
  console.error('❌ 帆软报表加载失败:', error);
  errorMessage.value = '无法连接到帆软服务器，请检查服务器地址和网络连接';
  showError.value = true;
  isLoading.value = false;
};

/**
 * 重新加载帆软报表
 */
const retryLoad = () => {
  console.log('🔄 重新加载帆软报表...');
  isRetrying.value = true;
  showError.value = false;
  isLoading.value = true;
  loadingHint.value = '正在重新连接...';
  
  // 重新设置iframe src
  setTimeout(() => {
    if (fanruanIframe.value) {
      const url = new URL(fanruanUrl.value);
      url.searchParams.set('_t', Date.now()); // 添加时间戳防止缓存
      fanruanIframe.value.src = url.toString();
    }
    isRetrying.value = false;
  }, 500);
  
  // 30秒后如果还在加载，显示错误提示
  setTimeout(() => {
    if (isLoading.value) {
      errorMessage.value = '加载超时，帆软服务器可能未响应';
      showError.value = true;
      isLoading.value = false;
    }
  }, 30000);
};

/**
 * 保存配置
 */
const saveConfig = () => {
  if (!configForm.value.fullUrl) {
    proxy.$message.warning('请填写帆软报表完整URL');
    return;
  }
  
  // 验证URL格式
  try {
    new URL(configForm.value.fullUrl);
  } catch (e) {
    proxy.$message.error('URL格式不正确，请检查');
    return;
  }
  
  // 保存到localStorage
  localStorage.setItem('fanruan_config', JSON.stringify(configForm.value));
  
  // 更新URL
  fanruanUrl.value = previewUrl.value;
  
  // 关闭对话框
  showConfigDialog.value = false;
  
  // 重新加载
  proxy.$message.success('配置已保存，正在重新加载...');
  retryLoad();
};

/**
 * 组件挂载
 */
onMounted(async () => {
  console.log('📊 实时大屏页面初始化...');
  
  // 初始化配置
  initConfig();
  
  // 30秒后如果还在加载，显示错误提示
  setTimeout(() => {
    if (isLoading.value) {
      errorMessage.value = '加载超时，帆软服务器响应时间过长';
      showError.value = true;
      isLoading.value = false;
    }
  }, 30000);
  
  // 初始化SignalR实时连接
  await initSignalR();
});

/**
 * 组件卸载
 */
onUnmounted(async () => {
  console.log('🔚 实时大屏页面卸载...');
  
  // 清除定时器
  if (pollingTimer) {
    clearInterval(pollingTimer);
    pollingTimer = null;
  }
  
  // 停止服务器端定时推送
  try {
    await proxy.http.post('/api/Dashboard/StopAutoPush');
    console.log('✅ 已停止服务器端定时推送');
  } catch (error) {
    console.warn('⚠️ 停止定时推送失败:', error.message);
  }
  
  // 断开SignalR连接
  if (connection) {
    try {
      await connection.invoke('LeaveGroup', 'Dashboard');
      await connection.stop();
      console.log('✅ SignalR连接已断开');
    } catch (error) {
      console.error('❌ 断开SignalR连接失败:', error);
    }
  }
});
</script>

<style scoped lang="less">
// 容器样式 - 全屏布局
.dashboard-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background: #1a1a1a;
}

// 帆软报表全屏显示
.fanruan-fullscreen {
  width: 100%;
  height: 100%;
  border: none;
  display: block;
}

// 加载遮罩层
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  z-index: 10;
  
  .loading-icon {
    color: #fff;
    animation: rotate 1.5s linear infinite;
  }
  
  .loading-text {
    margin-top: 20px;
    font-size: 18px;
    color: #fff;
    font-weight: 500;
  }
  
  .loading-hint {
    margin-top: 10px;
    font-size: 14px;
    color: rgba(255, 255, 255, 0.8);
  }
}

// 错误遮罩层
.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  z-index: 10;
  padding: 40px;
  overflow-y: auto;
  
  .error-icon {
    color: #fff;
    margin-bottom: 20px;
  }
  
  .error-title {
    font-size: 28px;
    font-weight: bold;
    color: #fff;
    margin-bottom: 15px;
  }
  
  .error-message {
    font-size: 16px;
    color: rgba(255, 255, 255, 0.9);
    margin-bottom: 30px;
    text-align: center;
  }
  
  .error-solutions {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 12px;
    padding: 25px;
    margin-bottom: 30px;
    max-width: 600px;
    width: 100%;
    
    h3 {
      font-size: 18px;
      color: #333;
      margin: 0 0 15px 0;
    }
    
    ol {
      margin: 0;
      padding-left: 20px;
      color: #666;
      
      li {
        margin: 10px 0;
        line-height: 1.6;
        font-size: 14px;
      }
    }
  }
  
  .error-actions {
    display: flex;
    gap: 15px;
    
    .el-button {
      padding: 12px 24px;
      font-size: 16px;
    }
  }
}

// 跨域提示遮罩层
.redirect-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  z-index: 10;
  padding: 40px;
  overflow-y: auto;
  
  .redirect-icon {
    color: #fff;
    margin-bottom: 20px;
  }
  
  .redirect-title {
    font-size: 28px;
    font-weight: bold;
    color: #fff;
    margin-bottom: 15px;
  }
  
  .redirect-message {
    font-size: 16px;
    color: rgba(255, 255, 255, 0.9);
    margin-bottom: 30px;
    text-align: center;
    line-height: 1.8;
  }
  
  .redirect-actions {
    display: flex;
    gap: 15px;
    margin-bottom: 30px;
    
    .el-button {
      padding: 12px 24px;
      font-size: 16px;
    }
  }
  
  .redirect-hint {
    max-width: 600px;
    width: 100%;
    
    p {
      margin: 8px 0;
      line-height: 1.6;
    }
  }
}

// 旋转动画
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>

